//封装操作redis的库

const red = require('../db/connections/redis_connect');

//设置key                      超时时间，默认一小时
function redisSet (key, value, timeout = 60 * 60) {
    if(typeof(value) === 'object') {
        value = JSON.stringify(value);
    }

    red.set(key, value);//设置redis数据
    red.expire(key, timeout)//给每个key设置过期时间
}

//获取redis数据
function redisGet (key) {
    return new Promise((resolve, reject) => {
        red.get(key, (error, value) => {
            if (error) {
                reject(error);
                return
            }

            if (value == null) {
                resolve(null);
                return
            }

            try {
                resolve(JSON.parse(value));
            } catch (err) {
                resolve(value);
            }
        });
    });
}

module.exports = {
    redisSet,
    redisGet
}